package rpc_netty.Client;

import rpc_1.object.RpcRequest;
import rpc_1.object.RpcResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RpcClientProxy_netty implements InvocationHandler{
        private NettyClient client;

        public RpcClientProxy_netty(NettyClient client){
            this.client=client;
        }


        @SuppressWarnings("unchecked")
        public <T> T getProxy(Class<T> clazz){
            return (T) Proxy.newProxyInstance(clazz.getClassLoader(),new Class<?>[]{clazz},this);
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //通过传来的参数，构造一个rpcRequest对象
            RpcRequest rpcRequest=new RpcRequest(method.getDeclaringClass().getName(),
                    method.getName(), args, method.getParameterTypes());
            //调用sendRequest方法，把rpcRequest通过socket发送给服务端，并等待结果
            RpcResponse o =(RpcResponse) client.sendRequest(rpcRequest);
            //拿到结果，返回
            return "StatusCode:"+o.getStatusCode()+"\n"
                    +"extraMessage:"+o.getMessage()+"\n"
                    +"data:"+o.getData();

        }

}
